/**
 * Created by admin on 2018/11/19.
 同盾查询
 */
 // 查询类型 // 扫描建议 // 分组信息 // 查询字段
 var  queryTypeData , scanSuggest ,groupInfo , searchCat ,ruleName=[];
apiready = function () {
    //初始化窗体
    iniFrom();
    // 初始化事件监听
    initEventListenner();
};

//查询方式
function iniFrom() {
  api.readFile({
      path:'widget://tongdun/tongdunQueryInfo.json'
  }, function(ret, err){
    var data=$api.strToJson(JSON.stringify(ret)).data;
    data=$api.strToJson(data);
    //查询方式
    queryTypeData=data.queryTypeData;
    // 扫描建议：
    scanSuggest=data.scanSuggest;
    // 分组信息：
    groupInfo=data.groupInfo;
    // 检索类型
     searchCat=data.searchCat;
  })

    api.readFile({
        path:'widget://tongdun/ruleName.json'
    }, function(ret, err){
      var roleNames=$api.strToJson(JSON.stringify(ret)).data;
      roleNames=$api.strToJson(roleNames).roleNames;
      ruleName=[];
      for(var i=0;i<roleNames.length;i++){
        var attr={};
        attr.text=roleNames[i];
        attr.value=roleNames[i];
        ruleName.push(attr)
      }
  })
}

function   initEventListenner() {
  //查询方式
  $api.addEvt($api.byId('queryType'), 'click', function(){viewSelect("查询方式",queryTypeData,$api.byId('queryType'));});
  // 扫描建议：
  $api.addEvt($api.byId('scanSuggest'), 'click', function(){viewSelect("扫描建议",scanSuggest,$api.byId('scanSuggest'));});
  // 分组信息：
  $api.addEvt($api.byId('groupInfo'), 'click', function(){viewSelect("分组信息",groupInfo,$api.byId('groupInfo'));});
  // 规则名称
  $api.addEvt($api.byId('ruleName'), 'click', function(){viewSelect("规则名称",ruleName,$api.byId('ruleName'),300);});
  // 检索类型
  $api.addEvt($api.byId('searchCat'), 'click', function(){viewSelect("检索类型",searchCat,$api.byId('searchCat'));});

  $api.addEvt($api.byId('search'), 'click', loadPgaeInfo);

  var starCalendar = new lCalendar();
  starCalendar.init({'trigger': '#startDate',    'type': 'date'  });
  var endCalendar = new lCalendar();
  endCalendar.init({'trigger': '#endDate',    'type': 'date'  });

}

//构建可选项
function viewSelect(title,items,el,rectH){
  var curValue=$api.val(el);
  var UIMultiSelector = api.require('UIMultiSelector');
  for(var item in items) {
    if(item.value==curValue) item.status="selected";
  }
  if(!rectH) rectH=185;
   UIMultiSelector.open({
     rect: {h: rectH },
     text: {title: title,leftBtn: '',rightBtn: '关闭'},
     max: 1 ,
     singleSelection: true,
     styles: {
         mask: 'rgba(0,0,0,0)',
         title: {bg: 'rgb(0,64,128)', color: 'rgb(184,209,5)',size: 25,h: 44 },
         leftButton: {w: 0,h: 0,marginT: 5,marginL: 8,color: 'rgb(0,0,0)',size: 20},
         rightButton: {w: 60,h: 35,marginT: 5,marginR: 8,color: 'rgb(0,0,0)',size: 20},
         item: {h: 35,active: 'rgb(201,118,126)',size: 20,lineColor: 'rgb(78,57,255)',textAlign: 'left'}
     },
     animation: true,
     items: items
 }, function(ret, err) {
      if (ret.eventType == 'clickLeft' || ret.eventType == 'clickRight') {
              UIMultiSelector.hide();
      }
      if (ret.eventType == 'clickItem') {
        $api.attr(el,'data', ret.items[0].value)
        $api.val(el,  ret.items[0].text);
      }
  });
}

// 查询
function loadPgaeInfo() {
          var startTime = $api.byId('startDate').value.trim();
          var endTime = $api.byId('endDate').value.trim();
          if(startTime) startTime=startTime.trim()+" 00:00:00";
          if(endTime) endTime=endTime.trim()+" 23:59:59";
          var invokeMode =$api.attr($api.byId('queryType'),'data');
          invokeMode=invokeMode?invokeMode:'';
          var decision = $api.attr($api.byId('scanSuggest'),'data');
          decision=decision?decision:'';
          var group = $api.attr($api.byId('groupInfo'),'data');
          group=group?group:'';
          var minScore = $api.byId('minScore').value.trim();
          minScore = minScore ? parseInt(minScore) : 0;
          var maxScore =  $api.byId('maxScore').value.trim();
          maxScore = maxScore ? parseInt(maxScore) : 100;

          var searchCat =$api.attr($api.byId('searchCat'),'data');
          searchCat = searchCat ? searchCat : '';
          var searchValue = $api.byId('searchValue').value.trim();
          searchValue = searchValue ? searchValue : '';
          var ruleName = $api.attr($api.byId('ruleName'),'data');
          ruleName = ruleName ? ruleName : '';
          if (startTime > endTime) {
              alert('开始时间不得大于结束时间');
              return false;
          }

          let isSpecial = false;
          if ((searchCat == 'report_id' && searchValue != '') || (searchCat == 'application_id' && searchValue != '')) {
            isSpecial = true;
          } else {
            isSpecial = false;
          }

          const timeBack = isSpecial ? false : timeChecked();
          if (timeBack) {
            alert(timeBack);
            return;
          }
      api.openWin({
  	    name: 'tongDunDataList',
  	    url: 'tongDunDataList.html',
  	    pageParam: {
  	        operationType: "queryReportList",
            startDate:startTime,
            endDate:endTime,
            invokeMode:invokeMode,
            decision:decision,
            searchCat:searchCat,
            searchValue:searchValue,
            ruleName:ruleName,
            group:group,
            minScore:minScore,
            maxScore:maxScore
  	    }
      })
}

// 时间检查函数
function timeChecked() {
  let back = false;
  const startDate = $api.byId('startDate').value.trim();
  const endDate = $api.byId('endDate').value.trim();
  const startTime = (new Date(startDate.replace(/-/g, '/'))).getTime();
  const endTime = (new Date(endDate.replace(/-/g, '/'))).getTime();

  const now = new Date();
  now.setFullYear(now.getFullYear() - 1);

  if (startTime < now.getTime()) {
    back = '对不起，目前支持的最早回溯时间为12个月。';
  } else if (endTime - startTime > 90 * 24 * 60 * 60 * 1000) {
    back = '对不起，目前支持的最大搜索时间范围为90天。';
  }
  return back;
}
